package com.baidu.health.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

public class ImageLabelUtils {
    public int testInterfaces(String url) throws Exception {
        //传入中文参数并设置编码格式
        String param = "{\"url\":\"中文\"}";
        param = URLEncoder.encode(param, "UTF-8");
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        int label = 3;
        try {
            URL realUrl = new URL(url + "?nrop");
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            //解析json对象
            Map map = JSON.parseObject(result, Map.class);
//            List<Object> list = JsonUtils.toList(map.get("fileList").toString());
            List<Object> list = JSON.parseArray(map.get("fileList").toString());
            for (Object o : list) {
                Map<String, Object> map2 = JSONObject.parseObject(JSON.toJSONString(o));
                label = (int) map2.get("label");
            }
            return label;
        } catch (Exception e) {
            e.printStackTrace();
            return label;
        }
    }
}

